package com.booking.springrestful.service.impl;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.booking.springrestful.domain.PatternLibrary;
import com.booking.springrestful.domain.PatternUploadReview;
import com.booking.springrestful.domain.Users;
import com.booking.springrestful.domain.dto.PatternReviewDto;
import com.booking.springrestful.domain.dto.PatternReviewSubmitDto;
import com.booking.springrestful.domain.vo.PatternReviewVo;
import com.booking.springrestful.exception.BusinessException;
import com.booking.springrestful.mapper.PatternLibraryMapper;
import com.booking.springrestful.mapper.PatternUploadReviewMapper;
import com.booking.springrestful.mapper.UsersMapper;
import com.booking.springrestful.resp.PageResult;
import com.booking.springrestful.resp.ResultCodeEnum;
import com.booking.springrestful.service.PatternLibraryService;
import com.booking.springrestful.service.PatternUploadReviewService;
import jdk.nashorn.internal.runtime.Undefined;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
* @author 13182
* @description 针对表【pattern_upload_review(用户上传纹样审核流程表)】的数据库操作Service实现
* @createDate 2025-10-15 13:24:56
*/
@Service
public class PatternUploadReviewServiceImpl extends ServiceImpl<PatternUploadReviewMapper, PatternUploadReview>
    implements PatternUploadReviewService {

    @Resource
    private PatternUploadReviewMapper uploadReviewMapper;

    @Override
    public void uploadPattern(PatternUploadReview uploadReview) {
        if (uploadReview.getUserId()==null){
            throw new BusinessException(ResultCodeEnum.INTERNAL_SERVER_ERROR,"未传递用户id");
        }
        uploadReviewMapper.insert(uploadReview);
    }

    @Resource
    private UsersMapper usersMapper;

    @Resource
    private PatternUploadReviewMapper patternUploadReviewMapper;

    @Resource
    private PatternLibraryMapper libraryMapper;

    /**
     * 分页查询纹样上传审核记录
     */
    @Override
    public PageResult<PatternReviewVo> getReviewList(Page<PatternReviewVo> page, PatternReviewDto dto) {
        QueryWrapper<PatternUploadReview> wrapper = new QueryWrapper<>();

        // 动态条件查询
        if (StringUtils.isNotBlank(dto.getName())) {
            wrapper.like("name", dto.getName());
        }
        if (StringUtils.isNotBlank(dto.getRegion())) {
            wrapper.like("region", dto.getRegion());
        }
        if (StringUtils.isNotBlank(dto.getType())) {
            wrapper.eq("type", dto.getType());
        }
        if (StringUtils.isNotBlank(dto.getDifficultyLevel())) {
            wrapper.eq("difficulty_level", dto.getDifficultyLevel());
        }
        if (StringUtils.isNotBlank(dto.getReviewStatus())) {
            wrapper.eq("review_status", dto.getReviewStatus());
        }

        wrapper.orderByDesc("upload_time");

        IPage<PatternUploadReview> resultPage = patternUploadReviewMapper.selectPage(
                new Page<>(page.getCurrent(), page.getSize()), wrapper);

        List<PatternReviewVo> voList = new ArrayList<>();
        for (PatternUploadReview record : resultPage.getRecords()) {
            PatternReviewVo vo = new PatternReviewVo();
            BeanUtils.copyProperties(record, vo);
            vo.setUploadTime(record.getUploadTime().toString());
            vo.setPatternRole((String) record.getPatternRole());

            // 查询用户名
            Users user = usersMapper.selectOne(new QueryWrapper<Users>().eq("userId", record.getUserId()));
            if (user != null) {
                vo.setRealname(user.getRealname());
            } else {
                vo.setRealname("未知用户");
            }

            voList.add(vo);
        }

        PageResult<PatternReviewVo> pageResult = new PageResult<>();
        pageResult.setTotal(resultPage.getTotal());
        pageResult.setData(voList);
        return pageResult;
    }

    /**
     * 提交审核：通过或驳回
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void submitReview(PatternReviewSubmitDto submitDto) {

        if (submitDto.getId() == null) {
            throw new BusinessException(ResultCodeEnum.INTERNAL_SERVER_ERROR, "审核记录ID不能为空");
        }

        PatternUploadReview review = patternUploadReviewMapper.selectById(submitDto.getId());
        if (review == null) {
            throw new BusinessException(ResultCodeEnum.INTERNAL_SERVER_ERROR, "审核记录不存在");
        }

        if (!"待审核".equals(review.getReviewStatus())) {
            throw new BusinessException(ResultCodeEnum.INTERNAL_SERVER_ERROR, "该记录已审核，无法重复操作");
        }

        if (StringUtils.isBlank(submitDto.getReviewStatus())) {
            throw new BusinessException(ResultCodeEnum.INTERNAL_SERVER_ERROR, "审核状态不能为空");
        }

        // 更新字段
        review.setReviewStatus(submitDto.getReviewStatus());
        review.setReviewerId(submitDto.getUserId());
        review.setReviewTime(new Date());

        if ("审核驳回".equals(submitDto.getReviewStatus())) {
            if (StringUtils.isBlank(submitDto.getRejectionReason())) {
                throw new BusinessException(ResultCodeEnum.INTERNAL_SERVER_ERROR, "驳回必须填写原因");
            }
            review.setRejectionReason(submitDto.getRejectionReason());
        } else if ("审核通过".equals(submitDto.getReviewStatus())) {
            // TODO: 可在此调用另一个服务，将该记录插入正式纹样库
            // Long patternId = patternLibraryService.saveFromReview(review);
            // review.setApprovedPatternId(patternId);

            PatternLibrary patternLibrary = new PatternLibrary();
            BeanUtil.copyProperties(review,patternLibrary);
            patternLibrary.setId(null);
            patternLibrary.setTemplateFilePath(review.getUploadedFilePath());
            patternLibrary.setStatus("正常");
            patternLibrary.setOriginalUploadUserId(review.getUserId());
            libraryMapper.insert(patternLibrary);

            review.setApprovedPatternId(Long.valueOf(patternLibrary.getOriginalUploadUserId()));

        } else {
            throw new BusinessException(ResultCodeEnum.INTERNAL_SERVER_ERROR, "无效的审核状态");
        }

        patternUploadReviewMapper.updateById(review);

    }



}




